package cn.com.nes.common.util;

import cn.hutool.core.util.StrUtil;

public class CompareStringMatch {

    private final String target;

    public CompareStringMatch(String target) {
        this.target = target;
    }

    public int compare(String s1, String s2) {
        if (s1.equals(target) && s2.equals(target)) {
            return 0;
        } else if (s1.equals(target)) {
            return -1;
        } else if (s2.equals(target)) {
            return 1;
        } else {
            int index1 = s1.indexOf(target);
            int index2 = s2.indexOf(target);
            if (index1 == -1 && index2 == -1) {
                return s1.compareTo(s2);
            } else if (index1 == -1) {
                return 1;
            } else if (index2 == -1) {
                return -1;
            } else {
                int freq1 = getFrequency(s1, target);
                int freq2 = getFrequency(s2, target);
                if (freq1 == freq2) {
                    return index1 - index2;
                } else {
                    return freq2 - freq1;
                }
            }
        }
    }

    private int getFrequency(String s, String target) {
        if (StrUtil.isBlank(target)) {
            return 0;
        }
        int count = 0;
        int index = s.indexOf(target);
        while (index != -1) {
            count++;
            index = s.indexOf(target, index + 1);
        }
        return count;
    }
}
